package com.mnnu.stategypattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
public class CustomerController {

    @Autowired
    public DefaultCustomerService defaultCustomerService;

    public Map<UserType, CustomerService> serviceMap;

    @Autowired
    public void initMap(List<CustomerService> services) {
        serviceMap = services.stream()
                .filter(customerService -> customerService.getClass().isAnnotationPresent(SupportUserType.class))
                .collect(Collectors.toMap(this::getUserType, Function.identity()));
        if (this.serviceMap.size() != UserType.values().length)
            throw new IllegalArgumentException("处理器未全部初始化");
    }

    public UserType getUserType(CustomerService customerService) {
        SupportUserType annotation = customerService.getClass().getAnnotation(SupportUserType.class);
        return annotation.value();
    }

    @GetMapping("/customer/{recharge}")
    public String customer(@PathVariable Integer recharge) {
        UserType userType = UserType.typeOf(recharge);
        CustomerService service = serviceMap.getOrDefault(userType, defaultCustomerService);
        return service.apply();
    }
}

